<?php namespace App\Admin\Template\Message;

//基础条件
use App\Core\Repository\Criterias\PaginateCriteria;
use App\Core\Repository\Criterias\SortCriteria;
//过滤器
use App\Core\Repository\Criterias\Filters\InputCriteria;
use App\Core\Repository\Criterias\Filters\InputKeywordsCriteria;
use App\Core\Repository\Criterias\Filters\InputTimeRangeCriteria;
use App\Jobs\SendMessage;

use Input;
use DB;
use Log;


trait Service {
    
    //基础服务
    use \App\Core\Service\Service;
    use \App\Core\Service\Services\All;
    use \App\Core\Service\Services\Indexer;
    use \App\Core\Service\Services\Creater;
    use \App\Core\Service\Services\Updater;
    use \App\Core\Service\Services\Changer;
    use \App\Core\Service\Services\Deleter;
    use \App\Core\Service\Services\Detailer;
    //操作日志
    use \App\Admin\Base\LogService;
    
    protected function bootService(){
        $this->bootBaseService();
        $this->setRepository(new Repository);
        $this->setMeta(new Meta);
        $this->repository = $this->getRepository();
    }
	
    //报修列表
    public function lists(){
        //过滤器
        $conditions = [
            new InputKeywordsCriteria('parameter_one'),
            new InputTimeRangeCriteria('created_at'),
            new InputCriteria('status'),
            new InputCriteria('type')
        ];
        $count = $this->repository->addCriterias($conditions)->count();
        $conditions[] = new PaginateCriteria();
        $conditions[] = new SortCriteria('id', 'DESC');
        $data = $this->repository->resetQuery()->resetCriteria()->addCriterias($conditions)->all();
        return $this->success([
            'count' => $count,
            'data' => $data
        ]);
    }

    //选择用户
    public function selectuser(){
        $userIds = Input::get('user_ids');
        $tempmessageId = Input::get('message_id');

        $tempmessage = DB::table('template_message_records')
            ->where('status','=',0)// 0未发送 1已经发送
            ->where('is_delete','=',0)// 1未发送 2已经发送
            ->where('id','=',$tempmessageId)
            ->first();
        if(!$tempmessage){
            return $this->inputError('消息已发送或被删除');
        }
        $res = DB::table('template_message_records')
            ->where('status','=',0)// 0未发送 1已经发送
            ->where('is_delete','=',0)// 1未发送 2已经发送
            ->where('id','=',$tempmessageId)
            ->update(['user_ids'=>$userIds]);
        if($res){
            return $this->success();
        }
        return $this->inputError('保存用户失败');
    }

    //给部分用户发送模版消息
    public function sendMessage(){
        $id = Input::get('id');
        $tempmessage = DB::table('template_message_records')
            ->where('status','=',0)// 0未发送 1已经发送
            ->where('is_delete','=',0)// 1未发送 2已经发送
            ->where('id','=',$id)
            ->first();
        if(!$tempmessage){
            return $this->inputError('消息已发送或被删除');
        }

        //通知接口发送模版消息
        $url = 'http://' . env('APP_API_HOST') .'/sys/sendMessageToApi';
        $data = array();
        $data['func'] = 'sendTemplateMessage';
        $data['data'] = json_encode(array(
            'tempmessageId'=>$id
        ));

        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $rest = curl_exec($ch);//运行curl
        curl_close($ch);
        return $this->success();
    }

    //给全部用户推送消息
    public function message(){
        $tempmessageId = Input::get('message_id');
        $tempmessage = DB::table('template_message_records')
            ->where('status','=',0)// 0未发送 1已经发送
            ->where('is_delete','=',0)// 1未发送 2已经发送
            ->where('id','=',$tempmessageId)
            ->first();
        if(!$tempmessage){
            return $this->inputError('消息已发送或被删除');
        }
        $userIds = 'all';

        DB::table('template_message_records')
            ->where('status','=',0)// 0未发送 1已经发送
            ->where('is_delete','=',0)// 1未发送 2已经发送
            ->where('id','=',$tempmessageId)
            ->update(['user_ids'=>$userIds]);

        //通知接口发送模版消息
        $urls = env('APP_API_HOST').'/sys/sendMessageToApi';
        $data = array();
        $data['func'] = 'sendTemplateMessage';
        $data['data'] = json_encode(array(
            'tempmessageId'=>$tempmessageId
        ));
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL, $urls);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $rest = curl_exec($ch);//运行curl
        curl_close($ch);
        return $rest;
    }

    #消息模版1租用成功 2归还成功 3助力结果
//    WX_TEMPLATE_1=hN_cKEm-gKUOcpIPYVv1-edhaxz81w75uj1TJpaSRnY
//    WX_TEMPLATE_2=Me4_olnp-4fpShBwT_O8s54PuxKfULtmb_ALish-7Oc
    //发送模版消息
    public function sendMessageToUser($userId,$type,$data){
        $post_data = array();
        $templateMessage = TemplateMessage::select('*')
            ->where('status','=',1)
            ->where('user_id','=',$userId)
            ->where('created_at','>', time()-24*7*3600+600)
            ->orderBy('id','asc')
            ->first();
        if(!$templateMessage){
//            Log::info('$userId:'.$userId);
            return;
        }
        $form_id = '';
        if($templateMessage->form_id){
            $form_id = $templateMessage->form_id;
            $templateMessage->times = 1;
            $templateMessage->status = 2;
        }else if($templateMessage->prepay_id){
            $form_id = $templateMessage->prepay_id;
            $templateMessage->times += 1;
            if($templateMessage->times > 2){
                $templateMessage->status = 2;
            }
        }else{
//            Log::info(json_encode($data));
            return;
        }
        $emphasis_keyword = '';
        $templateMessage->save();
        $page = '';
        switch ($type){
            case 1:
                $dataArr = array(
                    "keyword1"=>array(
                        "value"=>'产品-type1-包bao',
                        "color"=>"#173177"
                    ),
                    "keyword2"=>array(
                        "value"=>'永久免费',
                        "color"=>"#173177"
                    ),
                    "keyword3"=>array(
                        "value"=>'一万年',
                        "color"=>"#173177"
                    ),
                    "keyword4"=>array(
                        "value"=> date('Y-m-d H:i:s'),
                        "color"=>"#173177"
                    ),
                    "keyword5"=>array(
                        "value"=>'祖国首都北京',
                        "color"=>"#173177"
                    ),
                );
                $emphasis_keyword = "keyword2.DATA";
                $page = "pages/index/index";
                break;
            case 2:

//                产品名称
//                航拍无人机
//
//                租借时长
//                1小时
//
//                产生费用
//                1元
//
//                收费标准
//                ¥15/小时，封顶¥60/日 1小时内免费体验超出1小时15元/小时
//
//                归还时间
//                2015年12月10日 20:21
//
//                租借时间
//                2015年12月9日 12:40


                $dataArr = array(
                    "keyword1"=>array(
                        "value"=>$data['keyword1'],
                        "color"=>"#173177"
                    ),
                    "keyword2"=>array(
                        "value"=>$data['keyword2'],
                        "color"=>"#173177"
                    ),
                    "keyword3"=>array(
                        "value"=>$data['keyword3'],
                        "color"=>"#173177"
                    ),

                    "keyword4"=>array(
                        "value"=> '4小时内免费，超过4小时按10元/小时',
                        "color"=>"#173177"
                    ),

                    "keyword5"=>array(
                        "value"=>$data['keyword4'],
                        "color"=>"#173177"
                    ),
                    "keyword6"=>array(
                        "value"=>$data['keyword5'],
                        "color"=>"#173177"
                    ),
                );
                $emphasis_keyword = "keyword2.DATA";
                $page = "pages/index/index";
                break;
            case 3:

//                助力人
//                {{keyword1.DATA}} 你的好友
//
//                助力结果 已成功帮你助力xx步，为你走路抵金增加xx元
//                {{keyword2.DATA}}
//
//                发起时间 xx年xx月xx日 xx小时xx分
//                {{keyword3.DATA}}
//
//                温馨提示 可前面喜秒小程序"我的钱包"查看，好友抵金当天有效，赶快去花吧，不要浪费哟！！！；
//                {{keyword4.DATA}}

                $dataArr = array(
                    "keyword1"=>array(
                        "value"=>$data['keyword1'],
                        "color"=>"#173177"
                    ),
                    "keyword2"=>array(
                        "value"=>$data['keyword2'],
                        "color"=>"#173177"
                    ),
                    "keyword3"=>array(
                        "value"=>$data['keyword3'],
                        "color"=>"#173177"
                    ),
                    "keyword4"=>array(
                        "value"=> $data['keyword4'],
                        "color"=>"#173177"
                    )
                );
                $page = "pages/index/index";
                break;
            default : return;

        }
        $post_data = array (
            "touser"           => $templateMessage->open_id,
            //用户的 openID，可用过 wx.getUserInfo 获取
            "template_id"      => env('WX_TEMPLATE_'.$type),
            //小程序后台申请到的模板编号
            "page"             => "pages/index/index",
            //点击模板消息后跳转到的页面，可以传递参数
            "form_id"          => $form_id,
            //第一步里获取到的 formID
            "data"             => $dataArr,
            "emphasis_keyword" => $emphasis_keyword
            //需要强调的关键字，会加大居中显示
        );
//        Log::info(json_encode($post_data));
        $templateMsg = new WeixinTemplateMsg();
        $ret = $templateMsg->send($post_data);
        Log::info(json_encode($ret));
    }
}